﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;

namespace jacSocket
{
    public class JControler
    {
        private Socket _listener;
        private int Sport;

        private ManualResetEvent _connectDone = new ManualResetEvent(false);

        private jacEvent uiDisPlay;

        private System.Threading.SynchronizationContext ui;

        public JControler(jacEvent ud,int SP)
        {
            crossDomain cd = new crossDomain();
            cd.StartupPolicyServer();

            this.uiDisPlay = ud;
            Sport = SP;
            this.ui = System.Threading.SynchronizationContext.Current;
        }

        public void StartupSocketServer()
        {
            System.Threading.Thread t = new Thread(runServer);
            t.IsBackground = true;
            t.Start();
        }

        private void runServer()
        {
            _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _listener.Bind(new IPEndPoint(IPAddress.Any, Sport)); 
            _listener.Listen(100);

            while (true)
            {
                _connectDone.Reset();

                _listener.BeginAccept(new AsyncCallback(OnClientConnect), null);

                _connectDone.WaitOne();
            }
        }

        private void OnClientConnect(IAsyncResult async)
        {
            _connectDone.Set();

            ClientSocketPacket client = new ClientSocketPacket();

            client.Socket = _listener.EndAccept(async);

            ui.Post(this.uiDisPlay.userEnter, client);

            try
            {
                client.Socket.BeginReceive(client.Buffer, 0, client.Buffer.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), client);
            }
            catch
            {
                HandleException(client);
            }
        }

        private void OnDataReceived(IAsyncResult async)
        {
            ClientSocketPacket client = async.AsyncState as ClientSocketPacket;
            int count = 0;
            try
            {
                if (client.Socket.Connected)
                    count = client.Socket.EndReceive(async);
            }
            catch 
            {
                HandleException(client);
            }

            client.Stream.Write(client.Buffer, 0, count);

            Message message;

            while (client.Stream.Read(out message))
            {
                string content = UTF8Encoding.UTF8.GetString(message.Content, 0, message.Size);
                ui.Post(this.uiDisPlay.gotData, content);
            }

            try
            {
                if (client.Socket.Connected)
                    client.Socket.BeginReceive(client.Buffer, 0, client.Buffer.Length, 0, new AsyncCallback(OnDataReceived), client);
            }
            catch 
            {
                HandleException(client);
            }
        }

        public void SendMessage(string data, ClientSocketPacket client)
        {
            if (client.Socket.Connected)
            {
                byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
                Message message = new Message(1, 1, byteData);
                byteData = message.ToBytes();
                try
                {
                    client.Socket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnDataSent), client);
                }
                catch 
                {
                    HandleException(client);
                }
            }
            else
            {
                HandleException(client);
            }
        }

        private void OnDataSent(IAsyncResult async)
        {
            ClientSocketPacket client = async.AsyncState as ClientSocketPacket;

            try
            {
                client.Socket.EndSend(async);
            }
            catch 
            {
                HandleException(client);
            }
        }

        private void HandleException(ClientSocketPacket c)
        {
            c.Socket.Close();
            ui.Post(this.uiDisPlay.delUser,c);
        }
    }
}
